package com.egg.basic.controller.web;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.qrcode.QrCodeException;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.egg.common.core.model.controller.WebController;
import com.egg.common.util.FileUtil;
import com.egg.common.util.HttpServletUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author east
 */
@Slf4j
@Api(tags = WebController.API_PREFIX + "二维码")
@RestController
@RequestMapping("/qrcode")
public class WebQRCodeController extends WebController {


    @ApiOperation(value = "二维码图片生成")
    @GetMapping(value = "/image", produces = MediaType.IMAGE_PNG_VALUE)
    public void qrcodeImage(
            @ApiParam(value = "二维码内容 (如果是一个url需要拼接完整的http://或https://)", required = true) @RequestParam(value = "content") String content
            , @ApiParam(value = "二维码标题") @RequestParam(value = "title", required = false) String title
            , @ApiParam(value = "二维码LOGO") @RequestParam(value = "logo", required = false) MultipartFile logo
            , @ApiParam(value = "宽") @RequestParam(value = "width", required = false, defaultValue = "300") Integer width
            , @ApiParam(value = "长") @RequestParam(value = "height", required = false, defaultValue = "300") Integer height
            , @ApiParam(value = "边距1~4") @RequestParam(value = "margin", required = false, defaultValue = "2") Integer margin
    ) {
        QrConfig qrConfig = initQrConfig();
        if (ObjectUtil.isNotEmpty(width)) {
            qrConfig.setWidth(width);
        }
        if (ObjectUtil.isNotEmpty(height)) {
            qrConfig.setHeight(height);
        }
        if (ObjectUtil.isNotEmpty(margin)) {
            qrConfig.setMargin(margin);
        }
        createQRCode2Stream(content, title, FileUtil.convertToFile(logo), qrConfig);
    }

    private static QrConfig initQrConfig() {
        QrConfig config = new QrConfig(300, 300);
        // 设置边距，既二维码和背景之间的边距
        config.setMargin(2);
        // 设置前景色，既二维码颜色（黑色）
        config.setForeColor(Color.BLACK);
        // 设置背景色（白色）
        config.setBackColor(Color.WHITE);
        return config;
    }

    private void createQRCode2Stream(String content, String title, File logo, QrConfig qrConfig) {
        HttpServletResponse response = HttpServletUtil.getHttpServletResponse();
        if (null == response) {
            return;
        }
        createQRCode2Stream(content, title, logo, qrConfig, response);
    }

    /**
     * 生成到流
     *
     * @param content
     * @param qrConfig
     * @param response
     */
    private void createQRCode2Stream(String content, String title, File logo, QrConfig qrConfig, HttpServletResponse response) {
        try {
            if (null != logo) {
                qrConfig.setImg(logo);
            }
            BufferedImage generate = QrCodeUtil.generate(content, qrConfig);
            fillTitle(generate, title);
            ImgUtil.write(generate, ImgUtil.IMAGE_TYPE_PNG, response.getOutputStream());
        } catch (QrCodeException | IOException e) {
            log.error("生成二维码发生错误！ {}！", e.getMessage());
        }
    }

    /**
     * 填充标题
     *
     * @param generate
     * @param title
     */
    private void fillTitle(BufferedImage generate, String title) {
        if (ObjectUtil.isEmpty(title)) {
            return;
        }
        Graphics2D textGraphics = generate.createGraphics();
        Font font = new Font(Font.SANS_SERIF, Font.BOLD, 20);
        textGraphics.setFont(font);
        textGraphics.setColor(Color.BLACK);
        int titleWidth = textGraphics.getFontMetrics().stringWidth(title);
        int titleX = (generate.getWidth() - titleWidth) / 2;
        int titleY = generate.getHeight() - 5;
        textGraphics.drawString(title, titleX, titleY);
        textGraphics.dispose();
    }
}
